package com.example.controller;

import com.example.req.CategorySaveReq;
import com.example.req.DocSaveReq;
import com.example.service.DocService;
import com.example.utils.RequestContext;
import com.example.utils.Result;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

@RestController
public class DocController {

    @Autowired
    DocService docService;

    @GetMapping("/docList/{ebookId}")
    public Result findDoc(@PathVariable("ebookId") Long ebookId){
        return Result.success(docService.findDoc(ebookId));
    }

    @PostMapping("/doc")
    public Result saveDoc(@RequestBody @Valid DocSaveReq req) {
        docService.saveDoc(req);
        return Result.success();
    }

//    @DeleteMapping("/doc/{id}")
//    public Result deleteDoc(@PathVariable("id") Long id){
//        docService.deleteDoc(id);
//        return Result.success();
//    }

    @DeleteMapping("/doc/{ids}")
    public Result deleteDocByList(@PathVariable("ids") String ids){
        List<Long> docList = Arrays.asList((Long[])ConvertUtils.convert(ids.split(","),Long.class));
        docService.deleteDocByList(docList);
        return Result.success();
    }

    @GetMapping("/docContent/{id}")
    public Result findDocContent(@PathVariable("id") Long id){
        docService.updateDocView(id);
        return Result.success(docService.findDocContent(id));
    }

    @GetMapping("/doc/vote/{id}")
    public Result DocVote(@PathVariable("id") Long id, HttpServletRequest request){
        RequestContext.setRemoteAddr(request.getHeader("x-forwarded-for"));
        docService.updateDocVote(id);
        return Result.success();
    }

}
